package com.back.service.impl;

import com.back.model.dto.UserAnswerDTO;
import com.back.model.vo.QuestionsVo;
import com.back.service.ScoreService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class ScoreServiceImpl implements ScoreService {
    @Override
    public BigDecimal doScore(List<QuestionsVo> questionsVoList, List<UserAnswerDTO> userAnswerDTOList) {
        BigDecimal bigDecimal = new BigDecimal("0");
        Map<Integer, String> userAnswerDTOMap = new HashMap<>();
        for (UserAnswerDTO userAnswerDTO : userAnswerDTOList) {
            userAnswerDTOMap.put(userAnswerDTO.getQuestionId(), userAnswerDTO.getUserOption());
        }
        for (QuestionsVo questionsVo : questionsVoList) {
            String s = userAnswerDTOMap.get(questionsVo.getId());
            //单选
            if (0 == questionsVo.getType()) {
                questionsVo.setUerCorrectAnswer(s);
                if (questionsVo.getCorrectAnswer().equals(s)) {
                    bigDecimal = bigDecimal.add(questionsVo.getScore());
                }
            }
            //多选
            else if (1 == questionsVo.getType()) {
                List<String> userlist = Arrays.asList(s.split(","));
                List<String> multipleAnswers = questionsVo.getMultipleAnswers();
                questionsVo.setUerMultipleAnswers(userlist);
                int i = multiChoiceScoring(userlist, multipleAnswers);
                if (i == 1) {
                    bigDecimal = bigDecimal.add(questionsVo.getScore());
                } else if (i == 2) {
                    bigDecimal = bigDecimal.add(questionsVo.getScore().multiply(new BigDecimal("0.6")));
                }
            }
        }
        return bigDecimal;
    }

    /**
     * 返回1 全部选对 返回2 部分对，返回3选错或者多选或者没选
     *
     * @param list 用户选项
     * @param multipleAnswers 答案选项
     * @return 情况
     */
    private int multiChoiceScoring(List<String> list, List<String> multipleAnswers) {
        if (list.equals(multipleAnswers)) {
            return 1;
        }
        // 情况3：list中有multipleAnswers没有的元素
        // 创建multipleAnswers的Set用于快速查找
        Set<String> multipleAnswersSet = new HashSet<>(multipleAnswers);
        for (String item : list) {
            if (!multipleAnswersSet.contains(item)) {
                return 3;
            }
        }
        // 情况2：list是multipleAnswers的子集
        // 如果执行到这里，说明list中的所有元素都在multipleAnswers中
        // 还需要检查是否list的大小小于multipleAnswers（真正的子集）
        // 或者等于（完全相等，但情况1已经处理过，所以这里肯定是真子集或相等但顺序不同？）
        // 根据你的需求，如果完全相等已经返回1，那么这里可以返回2
        return 2;
    }
}

